//
//  FaceAuthController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/7/4.
//

import UIKit
import AVFoundation

class FaceAuthController: BaseViewController {
    
    // 初始化捕获会话
    var captureSession: AVCaptureSession!
    var previewLayer: AVCaptureVideoPreviewLayer!
    var photoOutput: AVCapturePhotoOutput!
    
    @IBOutlet weak var cameraButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNav()
        setupUI()
    }
    
    @IBAction func cameraAction(_ sender: Any) {
        let settings = AVCapturePhotoSettings()
        photoOutput.capturePhoto(with: settings, delegate: self)
    }
}

// MARK: - private
private extension FaceAuthController {
    
    func setupNav() {
        vhl_navBarBackgroundAlpha = 0
    }
    
    func setupUI() {
        setupAVCapture()
        view.bringSubviewToFront(cameraButton)
    }
    
    func setupAVCapture() {
        
        captureSession = AVCaptureSession()
        
        // 获取后置摄像头
        guard let camera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) else {
            return
        }
        
        do {
            // 创建输入对象
            let input = try AVCaptureDeviceInput(device: camera)
            
            // 将输入添加到会话中
            if captureSession.canAddInput(input) {
                captureSession.addInput(input)
            }
            
            photoOutput = AVCapturePhotoOutput()
            if captureSession.canAddOutput(photoOutput) {
                captureSession.addOutput(photoOutput)
            } else {
                print("Error: Could not add photo output to the session.")
            }
            
            // 创建预览层以显示相机内容
            previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            // 设置为全屏显示
            previewLayer.frame = CGRect(x: 0, y: 0, width: xScreenW, height: xScreenH)
            previewLayer.videoGravity = .resizeAspectFill
            
            view.layer.addSublayer(previewLayer)
            
            DispatchQueue.global().async {
                /// 异步线程
                // 开始会话
                self.captureSession.startRunning()
            }
            
        } catch {
            print("Error setting up camera input: \(error)")
        }
    }
    
    
    func uploadImage(_ image: UIImage) {
        YLHUD.showLottie()
        let object = AliOSSObject.init(image)
        AliOSSUtil.shared.uploadSingleObject(object) { bytesSent, totalBytesSent, totalBytesExpectedToSend in
            let progress = Double(totalBytesSent) / Double(totalBytesExpectedToSend)
            xLog("[上传] 图片上传进度 \(Int(progress*100))")
        } completion: { object, error in
            DispatchQueue.main.async { [self] in
                YLHUD.hideHUD()
                if error != nil {
                    YLHUD.showHint(.error, "上传失败")
                    xLog(error)
                    return
                }
                xLog(object.url)
                back()
            }
        }
    }
}

// MARK: - 拍照
extension FaceAuthController: AVCapturePhotoCaptureDelegate {
    
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        guard let imageData = photo.fileDataRepresentation(), let uiImage = UIImage(data: imageData) else { return }
        // 或者使用 .rightMirrored 取决于你的需求, 设置镜像
        let mirroredImage = UIImage(cgImage: uiImage.cgImage!, scale: uiImage.scale, orientation: .leftMirrored)
        // 使用 mirroredImage 做进一步处理或显示
        uploadImage(mirroredImage)
    }
}
